"use client";

import { NavBar, Toast, SearchBar } from "antd-mobile";
import { useState, useEffect } from "react";
import { DeleteOutline, CloseOutline } from "antd-mobile-icons";
import { useNavigate } from "react-router-dom";

import image1 from "/img(1)/image(1).png";
import image2 from "/img(4)/image(1).png";
import image3 from "/img(4)/image(2).png";
import image4 from "/img(4)/image.png";
const products = [
  {
    id: 1,
    name: "善托 霉拮吸入粉雾剂",
    image: image1,
    price: 168.0,
    oldPrice: 198.0,
    desc: "自营/93",
    stock: 20,
    category: "季节用药",
  },
  {
    id: 2,
    name: "美林 布洛芬小儿混悬液",
    image: image2,
    price: 168.0,
    oldPrice: 198.0,
    desc: "自营/93",
    stock: 20,
    category: "上海制药",
  },
  {
    id: 3,
    name: "小儿咳喘灵口服液",
    image: image3,
    price: 168.0,
    oldPrice: 198.0,
    desc: "自营/93",
    stock: 20,
    category: "儿童用药",
  },
  {
    id: 4,
    name: "善托 霉拮吸入粉雾剂",
    image: image1,
    price: 168.0,
    oldPrice: 198.0,
    desc: "自营/93",
    stock: 20,
    category: "季节用药",
  },
  {
    id: 5,
    name: "美林 布洛芬小儿混悬液",
    image: image4,
    price: 168.0,
    oldPrice: 198.0,
    desc: "自营/93",
    stock: 20,
    category: "上海制药",
  },
  {
    id: 6,
    name: "美林 布洛芬小儿混悬液",
    image: image4,
    price: 168.0,
    oldPrice: 198.0,
    desc: "自营/93",
    stock: 20,
    category: "上海制药",
  },
  {
    id: 7,
    name: " 布洛芬小儿混悬液",
    image: image4,
    price: 16.0,
    oldPrice: 18.0,
    desc: "自营/93",
    stock: 20,
    category: "上海制药",
  },
];
export default function Searchbar() {
  const [value, setValue] = useState("");
  const [history, setHistory] = useState<string[]>([]);
  const [filteredProducts, setFilteredProducts] = useState(products); // 新增

  // 初始化历史搜索
  useEffect(() => {
    const his = localStorage.getItem("search_history");
    if (his) setHistory(JSON.parse(his));
  }, []);

  // 保存历史到 localStorage
  const saveHistory = (arr: string[]) => {
    setHistory(arr);
    localStorage.setItem("search_history", JSON.stringify(arr));
  };

  // 搜索事件
  const onSearch = (val: string) => {
    if (!val.trim()) return;
    let arr = history.filter((item) => item !== val);
    arr = [val, ...arr];
    if (arr.length > 10) arr = arr.slice(0, 10); // 最多10条
    saveHistory(arr);
    setValue("");
    // 搜索 products
    const filtered = products.filter((item) =>
      item.name.includes(val.trim())
    );
    setFilteredProducts(filtered);
  };

  // 点击历史词
  const onHistoryClick = (val: string) => {
    setValue(val);
    // 也触发搜索
    const filtered = products.filter((item) =>
      item.name.includes(val.trim())
    );
    setFilteredProducts(filtered);
  };
  // 单个删除
  const removeHistory = (val: string) => {
    const newHistory = history.filter((item) => item !== val);
    saveHistory(newHistory);
  };

  // 清空历史
  const clearHistory = () => {
    saveHistory([]);
  };
  const navigate = useNavigate();
  const back = () => {
    navigate(-1);
  };
  return (
    <div>
      <NavBar onBack={back}>搜索</NavBar>
      <div>
        <SearchBar
          placeholder="请输入内容"
          showCancelButton
          value={value}
          onChange={setValue}
          onSearch={onSearch}
        />
      </div>
      <div style={{ margin: "16px 0" }}>
        <div
          style={{
            display: "flex",
            alignItems: "center",
            justifyContent: "space-between",
          }}
        >
          <span style={{ fontWeight: 600 }}>历史搜索</span>
          {history.length > 0 && (
            <span
              style={{ cursor: "pointer", color: "#888" }}
              onClick={clearHistory}
            >
              <DeleteOutline />
            </span>
          )}
        </div>
        <div
          style={{ display: "flex", flexWrap: "wrap", gap: 8, marginTop: 8 }}
        >
          {history.map((item) => (
            <div
              key={item}
              style={{
                background: "#f3f3f3",
                borderRadius: 8,
                padding: "4px 12px",
                cursor: "pointer",
                fontSize: 14,
              }}
              onClick={() => onHistoryClick(item)}
            >
              {item}
              <span style={{marginLeft:8}} onClick={(e) => { e.stopPropagation(); removeHistory(item); }}>
                <CloseOutline />
              </span>
            </div>
          ))}
        </div>
      </div>
      {/* 搜索结果展示 */}
      <h3>{
        filteredProducts.length === 0 ? "猜你想找：" : "搜索列表"
      }</h3>
      <div>
        {filteredProducts.length === 0 ? (
          <div style={{ color: "#888", textAlign: "center", marginTop: 32 }}>
            未找到相关商品
          </div>
        ) : (
          <div>
            {filteredProducts.map((item) => (
              <div
                key={item.id}
                style={{
                  display: "flex",
                  alignItems: "center",
                  background: "#fff",
                  borderRadius: 16,
                  boxShadow: "0 2px 8px rgba(0,0,0,0.06)",
                  padding: 18,
                  marginBottom: 20,
                  maxWidth: 420,
                  marginLeft: "auto",
                  marginRight: "auto",
                }}
              >
                <img
                  src={item.image}
                  alt={item.name}
                  style={{
                    width: 80,
                    height: 80,
                    objectFit: "cover",
                    borderRadius: 8,
                    marginRight: 18,
                    background: "#f6f6f6",
                  }}
                />
                <div style={{ flex: 1 }}>
                  <div
                    style={{
                      fontWeight: 600,
                      fontSize: 17,
                      color: "#222",
                      marginBottom: 8,
                    }}
                  >
                    {item.name}
                  </div>
                  <div
                    style={{ color: "#ff7b7b", fontSize: 14, marginBottom: 4 }}
                  >
                    {item.category}
                  </div>
                  <div style={{ color: "#f40", fontWeight: 600, fontSize: 16 }}>
                    ￥{item.price.toFixed(2)}
                  </div>
                </div>
              </div>
            ))}
          </div>
        )}
      </div>
    </div>
  );
}
